import os
import time
import platform
import requests
from datetime import datetime, timedelta
import json
from django.http import HttpResponse
from framework.settings import BASE_DIR, PROJECT_UA,PROJECT_BUILT,PROJECT_VERSION, PROJECT_FLAG,PROJECT_ADMIN_START_TIMESTAMP,TIMEOUT,PROJECT_SUPPORT_XCMS_MIN_VERSION
from app.utils.ZLMediaKit import ZLMediaKit
from app.utils.Settings import Settings
from app.utils.Config import Config
from app.utils.Logger import CreateLogger
from app.utils.OSSystem import OSSystem
from app.utils.Database import Database
from app.models import *
# BASE_DIR # xcnvs_admin目录的位置
BASE_PARENT_DIR = os.path.dirname(BASE_DIR)  # BASE_PARENT_DIR是软件根目录的位置
g_filepath_config_json = os.path.join(BASE_PARENT_DIR, "config.json")
g_filepath_config_ini = os.path.join(BASE_PARENT_DIR, "config.ini")
g_filepath_settings_json = os.path.join(BASE_DIR, "settings.json")

g_config = Config(filepath=g_filepath_config_json)
g_settings = Settings(filepath=g_filepath_settings_json)

__log_dir = os.path.join(BASE_PARENT_DIR, "log")
if not os.path.exists(__log_dir):
    os.makedirs(__log_dir)
g_logger = CreateLogger(filepath=os.path.join(__log_dir, "xcnvs_admin%s.log" % (datetime.now().strftime("%Y%m%d-%H%M%S"))),
                        is_show_console=False,
                        log_debug=g_config.logDebug)

g_logger.info("%s v%s,%s" % (PROJECT_UA,PROJECT_VERSION, PROJECT_FLAG))
g_logger.info(PROJECT_BUILT)
g_logger.info("g_filepath_config_json=%s" % g_filepath_config_json)
g_logger.info("g_filepath_config_ini=%s" % g_filepath_config_ini)
g_logger.info("g_filepath_settings_json=%s" % g_filepath_settings_json)
g_logger.info("config.json:%s" % g_config.getStr())
g_logger.info("settings.json:%s" % g_settings.getStr())
g_logger.info("logDebug=%d" % g_config.logDebug)
g_osSystem = OSSystem()

g_zlm = ZLMediaKit(logger=g_logger, config=g_config)
g_database = Database(logger=g_logger)
PROJECT_SUPPORT_XCMS_MIN_VERSION = PROJECT_SUPPORT_XCMS_MIN_VERSION
g_session_key_user = "user"
g_session_key_captcha = "captcha"

def f_parseGetParams(request):
    params = {}
    try:
        for k in request.GET:
            params.__setitem__(k, request.GET.get(k))
    except Exception as e:
        params = {}

    return params

def f_parsePostParams(request):
    params = {}
    for k in request.POST:
        params.__setitem__(k, request.POST.get(k))

    # 接收json方式上传的参数
    if not params:
        try:
            params = request.body.decode('utf-8')
            params = json.loads(params)
        except:
            params = {}

    return params
def f_parseRequestIp(request):
    try:
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR') # 备用方案
    except Exception as e:
        g_logger.error("f_parseRequestIp() error: %s"%str(e))
        ip = "0.0.0.0"
    return ip

def f_parseRequestPort(request):
    return 0
def f_sessionReadUser(request):
    user = request.session.get(g_session_key_user)
    return user

def f_sessionReadUserId(request):
    try:
        user_id = f_sessionReadUser(request).get("id")
    except:
        user_id = 0
    return user_id

def f_checkRequestSafe(request):
    ret = False
    msg = "未知错误"
    # 检查请求是否安全
    user_id = f_sessionReadUserId(request)
    if user_id:
        ret = True
        msg = "success"
    else:
        headers = request.headers
        Safe = headers.get("Safe")
        if Safe and Safe == g_config.xcnvsSafe:
            ret = True
            msg = "success"
        else:
            msg = "safe verify error"
    return ret,msg

def f_sessionLogout(request):
    if request.session.has_key(g_session_key_user):
        del request.session[g_session_key_user]
    if request.session.has_key(g_session_key_captcha):
        del request.session[g_session_key_captcha]

def f_responseJson(res):
    def json_dumps_default(obj):
        if hasattr(obj, 'isoformat'):
            return obj.isoformat()
        else:
            raise TypeError

    return HttpResponse(json.dumps(res, default=json_dumps_default), content_type="application/json")

def f_settingsReadData():
    return g_settings.data

def f_checkNode(node_code):
    ret = False
    msg = "未知错误"
    node = None
    node = NodeModel.objects.filter(code=node_code)
    if len(node) > 0:
        node = node[0]
        if node.state == 0:
            msg = "节点未同步"
        elif node.state == 1:
            ret = True
            msg = "success"
        elif node.state == 2:
            msg = "节点离线"
        else:
            msg = "节点版本低于%.3f" % PROJECT_SUPPORT_XCMS_MIN_VERSION
    else:
        msg = "节点不存在"

    return ret, msg, node

def f_authOpenIndex(node):
    is_online = False
    ret = False
    msg = "未知错误"
    info = {}
    try:
        headers = {
            "User-Agent": PROJECT_UA,
            "Content-Type": "application/json;",
            "Safe": node.xcms_safe
        }
        res = requests.get(url='%s/auth/openIndex' % node.address,
                           headers=headers, timeout=TIMEOUT)

        if res.status_code == 200:
            is_online = True

            res_result = res.json()
            msg = res_result.get("msg")
            if int(res_result.get("code", 0)) == 1000:
                info = res_result.get("info")
                ret = True
        else:
            raise Exception("status=%d" % res.status_code)
    except Exception as e:
        msg = str(e)

    return is_online,ret, msg, info

def f_openGetIndex(node):
    is_online = False
    ret = False
    msg = "未知错误"
    appInfo = {}
    osInfo = {}
    try:
        headers = {
            "User-Agent": PROJECT_UA,
            "Content-Type": "application/json;",
            "Safe": node.xcms_safe
        }
        res = requests.get(url='%s/open/getIndex' % node.address,
                           headers=headers, timeout=TIMEOUT)

        if res.status_code == 200:
            is_online = True

            res_result = res.json()
            msg = res_result.get("msg")
            if int(res_result.get("code", 0)) == 1000:
                appInfo = res_result.get("appInfo")
                osInfo = res_result.get("osInfo")
                ret = True
        else:
            raise Exception("status=%d" % res.status_code)
    except Exception as e:
        msg = str(e)

    return is_online,ret, msg, appInfo,osInfo

def f_syncNode(code=None):
    g_logger.info("f_syncNode() code=%s"%str(code))
    success_count = 0
    error_count = 0
    if code:
        # 指定节点
        nodes = []
        node = NodeModel.objects.filter(code=code).first()
        nodes.append(node)
    else:
        # 所有节点
        nodes = NodeModel.objects.all()

    for node in nodes:
        __is_online = False
        __ret = False
        __msg = "未知错误"

        try:
            __is_online, __ret, __msg, __appInfo, __osInfo = f_openGetIndex(node)
            if __is_online:
                if __ret:
                    project_version = float(__appInfo.get("project_version", 0))
                    node.version = project_version
                    node.flag = __appInfo.get("project_flag")
                    node.system_name = __osInfo.get("system_name")
                    node.machine_node = __osInfo.get("machine_node")
                    if project_version < PROJECT_SUPPORT_XCMS_MIN_VERSION:
                        node.state = 3
                        raise Exception("节点版本低于%.3f"%PROJECT_SUPPORT_XCMS_MIN_VERSION)
                else:
                    node.state = 3
                    raise Exception("节点版本低于%.3f"%PROJECT_SUPPORT_XCMS_MIN_VERSION)
            else:
                node.state = 2
                raise Exception("节点离线")

            __is_online, __ret, __msg, __info = f_authOpenIndex(node)
            if __is_online:
                if __ret:
                    node.machine_mac = __info.get("machineMac")
                    node.is_auth = int(__info.get("isAuth", 0))
                    node.is_multi_process = int(__info.get("isMultiProcess", 0))
                    node.max_count = int(__info.get("maxCount", 0))
                    node.desc = __info.get("desc")
                    try:
                        del __info["acActiveCode"]
                    except:
                        pass
                    node.auth_info = json.dumps(__info)
                    node.state = 1

                    __ret = True
                    __msg = "success"
                else:
                    node.state = 3
                    raise Exception("节点版本低于%.3f"%PROJECT_SUPPORT_XCMS_MIN_VERSION)
            else:
                node.state = 2
                raise Exception("节点离线")

        except Exception as e:
            __msg = str(e)
            g_logger.error("f_syncNode() node.code=%s,msg=%s" % (node.code, __msg))

        if __ret:
            node.last_update_time = datetime.now()
            node.save()
            success_count += 1
        else:
            node.last_update_time = datetime.now()
            node.save()
            error_count += 1

    ret = True
    msg = "成功%d条，失败%d条" % (success_count, error_count)

    g_logger.info("f_syncNode() ret=%d,msg=%s"%(ret,msg))

    return ret, msg


